from PyQt5.QtWidgets import (QMessageBox, QButtonGroup, QDialog, QVBoxLayout, 
                           QTableWidgetItem, QPushButton, QLabel)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.uic import loadUi
from src.utils.ui_utils import center_window
from src.models.user_model import UserInfo, UserModel
from src.models.product_model import ProductModel
from src.models.order_model import OrderModel

class UserInfoEditDialog(QDialog):
    """用户信息编辑对话框"""
    
    def __init__(self, parent, user_info):
        super().__init__(parent)
        self.user_info = user_info
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        # 加载UI文件
        ui_widget = loadUi('src/ui/user_edit.ui')
        
        # 设置窗口属性
        self.setWindowTitle(ui_widget.windowTitle())
        self.setFixedSize(ui_widget.size())
        self.setStyleSheet(ui_widget.styleSheet())
        
        # 获取UI中的控件
        self.usernameInput = ui_widget.usernameInput
        self.genderCombo = ui_widget.genderCombo
        self.ageInput = ui_widget.ageInput
        self.saveButton = ui_widget.saveButton
        self.cancelButton = ui_widget.cancelButton
        
        # 设置当前用户信息
        self.usernameInput.setText(self.user_info.username)
        
        # 设置当前性别
        current_gender = self.user_info.gender
        if current_gender in ["未设置", "男", "女"]:
            self.genderCombo.setCurrentText(current_gender)
    
        # 设置当前年龄
        if self.user_info.age > 0:
            self.ageInput.setText(str(self.user_info.age))
        
        # 连接按钮事件
        self.saveButton.clicked.connect(self.save_changes)
        self.cancelButton.clicked.connect(self.reject)

        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(ui_widget)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
    
        # 居中显示
        center_window(self)
        
    def save_changes(self):
        """保存修改"""
        username = self.usernameInput.text().strip()
        gender = self.genderCombo.currentText()
        age_text = self.ageInput.text().strip()
        
        if not username:
            QMessageBox.warning(self, '警告', '请输入用户名！')
            self.usernameInput.setFocus()
            return
            
        age = 0
        if age_text:
            try:
                age = int(age_text)
                if age < 0 or age > 150:
                    QMessageBox.warning(self, '警告', '请输入有效的年龄（0-150）！')
                    self.ageInput.setFocus()
                    return
            except ValueError:
                QMessageBox.warning(self, '警告', '年龄必须是数字！')
                self.ageInput.setFocus()
                return
        
        if UserModel.update_user_info(self.user_info.id, username, gender, age):
            self.user_info.username = username
            self.user_info.gender = gender
            self.user_info.age = age
            
            QMessageBox.information(self, '成功', '个人信息修改成功！')
            self.accept()
        else:
            QMessageBox.warning(self, '错误', '个人信息修改失败，请稍后重试！')

class UserMainView:
    """普通用户主界面视图类"""
    
    def __init__(self, controller):
        self.controller = controller
        self.ui = loadUi('src/ui/user_main.ui')
        
        # 创建按钮组
        self.nav_button_group = QButtonGroup()
        self.nav_button_group.addButton(self.ui.shopButton)
        self.nav_button_group.addButton(self.ui.orderButton)
        self.nav_button_group.addButton(self.ui.userButton)
        
        # 连接导航按钮事件
        self.ui.shopButton.clicked.connect(self.on_shop_clicked)
        self.ui.orderButton.clicked.connect(self.on_order_clicked)
        self.ui.userButton.clicked.connect(self.on_user_clicked)
        self.ui.logoutButton.clicked.connect(self.on_logout_clicked)
        
        # 连接个人信息编辑按钮
        self.ui.editInfoButton.clicked.connect(self.on_edit_info_clicked)
        
        # 设置表格行高
        self.setup_tables()
        
        center_window(self.ui)
        
    def setup_tables(self):
        """设置表格行高"""
        # 设置商品表格行高
        self.ui.productTable.verticalHeader().setDefaultSectionSize(70)
        self.ui.productTable.verticalHeader().setMinimumSectionSize(60)
        
        # 设置订单表格行高
        self.ui.orderTable.verticalHeader().setDefaultSectionSize(70)
        self.ui.orderTable.verticalHeader().setMinimumSectionSize(60)

    def show(self):
        """显示主界面"""
        self.ui.show()
        # 默认显示商品页面并加载商品
        self.ui.stackedWidget.setCurrentWidget(self.ui.shopPage)
        self.load_products()
        
    def hide(self):
        """隐藏主界面"""
        self.ui.hide()
        
    def set_welcome_message(self, username):
        """设置欢迎信息"""
        self.ui.welcomeLabel.setText(f"欢迎回来，{username}！")
        
    def on_shop_clicked(self):
        """逛店铺按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.shopPage)
        self.load_products()
        
    def on_order_clicked(self):
        """订单信息按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.orderPage)
        self.load_orders()
        
    def on_user_clicked(self):
        """用户信息按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.userPage)
        self.update_user_info_display()
        
    def update_user_info_display(self):
        """更新用户信息显示"""
        current_user = self.controller.current_user
        if current_user and isinstance(current_user, UserInfo):
            user_info_text = f"""基本信息

用户ID：{current_user.id}
用户名：{current_user.username}
手机号：{current_user.phone}
性别：{current_user.gender}
年龄：{current_user.get_age_display()}
角色：{current_user.get_role_name()}

点击下方按钮可以修改个人信息"""
            self.ui.userInfoLabel.setText(user_info_text)
        
    def load_products(self):
        """加载商品数据"""
        try:
            products = ProductModel.get_all_products()
            self.ui.productTable.setRowCount(len(products))
            
            for row, product in enumerate(products):
                self.ui.productTable.setItem(row, 0, QTableWidgetItem(product.product_name))
                self.ui.productTable.setItem(row, 1, QTableWidgetItem(f"{product.price:.2f}"))
                self.ui.productTable.setItem(row, 2, QTableWidgetItem(str(product.sales)))
                
                # 创建购买按钮
                buy_button = QPushButton("选购")
                buy_button.setProperty("class", "buyButton")
                
                # 使用内部函数避免闭包问题
                def create_buy_handler(p):
                    return lambda: self.buy_product(p)
                
                buy_button.clicked.connect(create_buy_handler(product))
                self.ui.productTable.setCellWidget(row, 3, buy_button)
                    
        except Exception as e:
            QMessageBox.warning(self.ui, "错误", f"加载商品失败：{str(e)}")

    def buy_product(self, product):
        """购买商品"""
        if not self.controller.current_user:
            QMessageBox.warning(self.ui, "错误", "请先登录！")
            return
            
        reply = QMessageBox.question(
            self.ui, 
            '确认购买', 
            f'确定要购买 "{product.product_name}" 吗？\n价格：{product.price:.2f}元',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            current_user = self.controller.current_user
            order_id = OrderModel.create_order(
                product.product_name,
                product.price,
                current_user.phone,
                current_user.username
            )
            
            if order_id:
                ProductModel.increment_sales(product.id)
                QMessageBox.information(self.ui, "购买成功", f"订单创建成功！\n订单号：{order_id}\n预计30分钟内送达")
                # 删除刷新代码，购买后不自动刷新
            else:
                QMessageBox.warning(self.ui, "购买失败", "创建订单失败，请稍后重试！")
        
    def load_orders(self):
        """加载用户订单数据"""
        try:
            if not self.controller.current_user:
                return
                
            orders = OrderModel.get_orders_by_customer(self.controller.current_user.phone)
            self.ui.orderTable.setRowCount(len(orders))
            
            for row, order in enumerate(orders):
                self.ui.orderTable.setItem(row, 0, QTableWidgetItem(str(order.id)))
                self.ui.orderTable.setItem(row, 1, QTableWidgetItem(order.product_name))
                self.ui.orderTable.setItem(row, 2, QTableWidgetItem(f"{order.price:.2f}"))
                
                # 状态项带颜色
                status_item = QTableWidgetItem(order.get_status_text())
                if order.delivery_status == 0:
                    status_item.setBackground(QColor(255, 165, 0))  # 橙色 - 待派发
                elif order.delivery_status == 1:
                    status_item.setBackground(QColor(135, 206, 235))  # 蓝色 - 派送中
                else:
                    status_item.setBackground(QColor(144, 238, 144))  # 绿色 - 已完成
                self.ui.orderTable.setItem(row, 3, status_item)
                
                # 下单时间
                if order.order_time:
                    time_str = order.order_time.strftime("%Y-%m-%d %H:%M:%S")
                    self.ui.orderTable.setItem(row, 4, QTableWidgetItem(time_str))
                else:
                    self.ui.orderTable.setItem(row, 4, QTableWidgetItem("未知"))
                
                # 操作按钮
                if order.delivery_status == 1:  # 派送中，可以确认收货
                    confirm_button = QPushButton("确认收货")
                    confirm_button.setProperty("class", "confirmButton")
                    
                    # 使用内部函数避免闭包问题
                    def create_confirm_handler(o):
                        return lambda: self.confirm_order(o)
                    
                    confirm_button.clicked.connect(create_confirm_handler(order))
                    self.ui.orderTable.setCellWidget(row, 5, confirm_button)
                else:
                    status_label = QLabel("已完成" if order.delivery_status == 2 else "等待派送")
                    status_label.setAlignment(Qt.AlignCenter)
                    self.ui.orderTable.setCellWidget(row, 5, status_label)
            
        except Exception as e:
            QMessageBox.warning(self.ui, "错误", f"加载订单失败：{str(e)}")
            
    def confirm_order(self, order):
        """确认收货"""
        reply = QMessageBox.question(
            self.ui, 
            '确认收货', 
            f'确定已收到订单 "{order.product_name}" 吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            if OrderModel.confirm_delivery(order.id):
                QMessageBox.information(self.ui, "成功", "已确认收货，感谢您的使用！")
                # 删除刷新代码，确认收货后不自动刷新
            else:
                QMessageBox.warning(self.ui, "失败", "确认收货失败，请稍后重试！")
        
    def on_edit_info_clicked(self):
        """修改个人信息按钮点击事件"""
        current_user = self.controller.current_user
        if current_user:
            edit_dialog = UserInfoEditDialog(self.ui, current_user)
            if edit_dialog.exec_() == QDialog.Accepted:
                # 更新用户信息显示
                self.update_user_info_display()
                # 更新欢迎信息
                self.set_welcome_message(current_user.username)

    def on_logout_clicked(self):
        """退出登录按钮点击事件"""
        reply = QMessageBox.question(
            self.ui, 
            '确认退出', 
            '确定要退出登录吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.controller.logout()